import ReactDOM from "react-dom/client";
import "./index.css";

import Chart, { ChartType, ProductLevel } from "./components/Chart";
import { IProduct } from "./stores/ProductStore";
import { unsafeWindow } from "$";

// @ts-ignore
const $ = unsafeWindow.jQuery;

const site = unsafeWindow.location.href;
const url = new URL(site);

// 图表类型 type
let type: ChartType = null;
if (url.host == "www.cpubenchmark.net") {
  type = "CPU";
}
if (url.host == "www.videocardbenchmark.net") {
  type = "GPU"
}

// 产品定位级别 level
let level: ProductLevel = null;
const levels: ProductLevel[] = [
  "high_end", 
  "mid_range", 
  "midlow_range", 
  "low_end"
];
let result = levels.find(level => level != null && url.pathname.indexOf(level) >= 0);
if (result != undefined) {
  level = result;
}
else {
  console.warn("未找到产品定位！");
}

// 更新时间（可能没有）
let updateTime: string | undefined = undefined;

// 获取产品信息 IProduct[]
let products: IProduct[] = [];
let lis = $("#mark li");
for (let liIndex = 0; liIndex < lis.length; liIndex++) {
  let li = lis[liIndex];

  let onclickScript: string = $(".more_details", li).attr("onclick");
  let params = onclickScript.substring(2, onclickScript.length - 2).trim();
  let paramList = params.split(", ");
  let details = paramList.slice(1).map((param) => {
    if (param == 'null') return null;
    if (param == 'undefined') return undefined;
    return param;
  });

  let mark = $(".count", li).text().replace(",", "");
  let price = $(".price-neww", li)
    .text()
    .replace(",", "")
    .replace("$", "")
    .replace("*", "");
  
  let product = {
    id: Number(li.id.substring(2)),
    link: $("a", li).attr("href"),
    name: $(".prdname", li).text(),
    mark: parseInt(mark),
    price: price == "NA" ? -1 : parseInt(price),
    details: details,
  } as IProduct;
  products.push(product);
}
console.info("获取产品信息：", products);

// 创建挂载点
const markId = "mark"; // mark
let mark = document.getElementById(markId);
if (mark == null) {
  mark = document.createElement("div");
  mark.id = markId;
  document.body.append(mark);
}

// 构建ReactDOM
let app = ReactDOM.createRoot(mark, {});

// 开始渲染
app.render(
  <Chart type={type} level={level} updateTime={updateTime} data={products} />
);
